import { useSimpleMemo } from '@/components';
import { COL_KEYS } from '@/constants/componentKeys';
import { isEqualStrictDeep, pick, simpleMerge } from '@/utils';
import { Col, Row } from 'antd';
import * as PropTypes from 'prop-types';
import React, { memo, useContext } from 'react';
import FieldComponent from './FieldComponent';
import { defaultCol, FormContext, FormProvider } from './shared';

FieldColsItem = memo(FieldColsItem, isEqualStrictDeep);

function FieldColsItem(props) {
  const { form, onCol } = useContext(FormContext);
  const { colProps, getColProps, ...itemOption } = props;

  const { hidden = false, ...currProps } = useSimpleMemo(onCol([props, props.index, form], getColProps, colProps));

  const [currColProps, extItemProps] = pick(currProps, COL_KEYS);
  const currItemProps = useSimpleMemo(simpleMerge(itemOption, extItemProps));

  if (hidden) return null;

  return (
    <Col {...currColProps}>
      <FieldComponent {...currItemProps} />
    </Col>
  );
}

FieldCols = memo(FieldCols, isEqualStrictDeep);

/** 用响应式布局渲染表单字段  */
function FieldCols(props) {
  let {
    fields,

    gutter,
    rowProps,
    children,

    onMapItem,

    ...rest
  } = props;

  return (
    <FormProvider
      useKeys={['labelSpan', 'wrapperSpan']}
      useProps={['col']}
      gutter={0}
      colProps={defaultCol}
      labelSpan={8}
      wrapperSpan={16}
      {...rest}
    >
      <Row gutter={gutter} {...rowProps}>
        {fields.map((item, index) => (
          <FieldColsItem key={index} index={index} {...(onMapItem?.(item) || item)} />
        ))}
        {children}
      </Row>
    </FormProvider>
  );
}

FieldCols.propTypes = {
  /** 字段配置 */
  fields: PropTypes.array,

  /** AntD的form实例 */
  form: PropTypes.object,

  /** Row 的参数 gutter */
  gutter: PropTypes.number,

  /** Row 的参数 */
  rowProps: PropTypes.object,

  /** Col 的参数 */
  colProps: PropTypes.object,

  /** Form.Item 的参数 labelCol.xs.span */
  labelSpan: PropTypes.any,

  /** Form.Item 的参数 wrapperCal.xs.span */
  wrapperSpan: PropTypes.any,

  /** Form.Item 的参数 */
  itemProps: PropTypes.object,

  /** 字段输入组件的参数 */
  fieldProps: PropTypes.object,

  /** Col 用函数动态生成的参数 */
  onCol: PropTypes.func,

  /** Form.Item 用函数动态生成的参数 */
  onItem: PropTypes.func,

  /** 字段输入组件 用函数动态生成的参数 */
  onField: PropTypes.func,

  /** 其他内容跟随在fields之后 */
  children: PropTypes.node,
};

export default FieldCols;
